﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using Concordia.Models.cs_Logon;
using Concordia.ViewModels;

namespace Concordia.Controllers
{
    public class cs_LogonController : Controller
    {
        //
        // GET: /cs_Logon/

        public ActionResult cs_Logon()
        {
            return View();
        }

        [HttpPost]
        public ActionResult cs_Logon(cs_Logon model, String returnUrl)
        {
            if (!ModelState.IsValid) return View();
            
            //Set IP address
            model.IP = Request.UserHostAddress;

            //Set reference varables
            int? nLoanKey = -1; int? nBorrowerKey = -1; Boolean? nIsValid = false; String nMessage = ""; //n => nullable

            var context = new cs_LogonDataContext();
            context.WEB_INS_BORROWER_LOGIN(model.IP, model.username, model.password, ref nLoanKey, ref nBorrowerKey, ref nIsValid, ref nMessage);

            //Store Session Info - Debated between this and query string...Sessions won...
            var vm = new AccountViewModel();
            vm.LoanKey = Convert.ToInt32(nLoanKey);
            vm.BorrowerKey = Convert.ToInt32(nBorrowerKey);
            vm.Now = DateTime.Now;

            Session["AccountViewModel"] = vm;

            if (nIsValid == true)
            {
                FormsAuthentication.SetAuthCookie(model.username, false);

                //used if they are relogging in...
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }

                //Main landing page after login
                return RedirectToAction("cs_Logged_Home", "cs_Logged_Home");



            }
            
            return View();
        }
    }
}
